package com.guozinhs.auto.util.image;

import cn.hutool.core.util.StrUtil;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.File;
import java.io.IOException;
import java.util.Objects;

/**
 * 图片处理工具类
 *
 * @Author: GuoZi
 * @Date: 2022/2/11 13:17
 */
public class ImageUtils {

    public static BufferedImage read(String path) {
        if (StrUtil.isBlank(path)) {
            return null;
        }
        File file = new File(path);
        if (!file.exists()) {
            return null;
        }
        try {
            return ImageIO.read(file);
        } catch (IOException e) {
            System.out.println("文件读取异常: " + e.getMessage());
        }
        return null;
    }

    public static void write(String path, Image image) {
        if (StrUtil.isBlank(path) || Objects.isNull(image)) {
            return;
        }
        File file = new File(path);
        if (!file.exists()) {
            file.getParentFile().mkdirs();
        }
        try {
            ImageIO.write((RenderedImage) image, "png", file);
        } catch (IOException e) {
            System.out.println("文件写入异常: " + e.getMessage());
        }
    }

    public static Image readFromClipboard() {
        // 从剪贴板读取图像
        Clipboard systemClipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
        Transferable contents = systemClipboard.getContents(null);
        if (Objects.nonNull(contents) && contents.isDataFlavorSupported(DataFlavor.imageFlavor)) {
            try {
                Image image = (Image) contents.getTransferData(DataFlavor.imageFlavor);
                image.getWidth(null);
                return image;
            } catch (UnsupportedFlavorException | IOException e) {
                System.out.println("剪贴板图片读取异常: " + e.getMessage());
            }
        }
        return null;
    }

    public static void write2Clipboard(final Image image) {
        // 写图像到剪贴板
        Transferable trans = new Transferable() {
            @Override
            public DataFlavor[] getTransferDataFlavors() {
                return new DataFlavor[]{DataFlavor.imageFlavor};
            }

            @Override
            public boolean isDataFlavorSupported(DataFlavor flavor) {
                return DataFlavor.imageFlavor.equals(flavor);
            }

            @Override
            public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException {
                if (isDataFlavorSupported(flavor)) {
                    return image;
                }
                throw new UnsupportedFlavorException(flavor);
            }
        };
        Toolkit.getDefaultToolkit().getSystemClipboard().setContents(trans, null);
    }

}
